package com.example.demo.controller;

import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.vo.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    //查询所有用户
    @GetMapping("/select")
    public Result select(){
        Result result = userService.select();
        return result;
    }

    //用户登陆
    @GetMapping("/login/{username}/{userpwd}")
    public Result login(@PathVariable String username, @PathVariable String userpwd, HttpServletRequest request){
        System.out.println(username);
        System.out.println(userpwd);
        Result result=userService.login(username,userpwd,request);
        return result;
    }

    //管理员登陆
    @GetMapping("/adminlogin/{username}/{userpwd}")
    public Result adminlogin(@PathVariable String username, @PathVariable String userpwd, HttpServletRequest request){
        System.out.println(username);
        System.out.println(userpwd);
        Result result=userService.adminlogin(username,userpwd,request);
        return result;
    }

    @GetMapping("/logout")
    public Result a(HttpServletRequest request){
        HttpSession session = request.getSession();
        Enumeration em = request.getSession().getAttributeNames();
        while(em.hasMoreElements()){
            request.getSession().removeAttribute(em.nextElement().toString());
        }
        return Result.success();
    }

    @GetMapping("/session")
    public Result GetSession(HttpServletRequest request){
        Map<String,Object> map= new HashMap<>();
        HttpSession session = request.getSession();
        //获取session的值
        Enumeration enumeration = session.getAttributeNames();
        while (enumeration.hasMoreElements()){
            String name=enumeration.nextElement().toString();
            Object value=session.getAttribute(name);
            map.put(name, value);
        }
        return Result.success(map);
    }
}
